const { Sequelize } = require("sequelize");
const tunnel = require("tunnel-ssh");

// sh
// ssh -L 3307:localhost:3306 -i C:/Users/administrator/.ssh/id_rsa ubuntu@43.138.54.58

const sshTunnelOptions = {
  keepAlive: true,
  user: "ubuntu",
  host: "43.138.54.58",
  password: "jPwQMIhOha",
  port: 22001,
  dstHost: "mysql",
  dstPort: 3306,
  localHost: "localhost",
  localPort: 3307,
  timeout: 60000, // 增加SSH连接超时

};

const sequelizeConfig = {
  dialect: "mysql",
  host: "localhost",
  port: 3307,
  username: "root",
  password: "91vDQhMgF9wzZlYf/MTUiZzAebT9D8Yi",
  database: "server",
  define: {
    // 使用自定义的表名
    freezeTableName: true,
    // 自动生成时间戳 -小驼峰式
    timestamps: true,
    // 表名小驼峰
    underscored: false,
  },
  connectTimeout: 60000, // 增加数据库连接超时
};

module.exports = async (app) => {
  try {
    console.log("Starting SSH tunnel...");
    try {
      const server = await tunnel(sshTunnelOptions);
      console.log("SSH tunnel established.");

      server.on("error", function (err) {
        console.error("Something bad happened:", err);
      });
    } catch (error) {
      console.log("error", error);
    }


    try {
        // 验证数据库连接
        const sequelize = new Sequelize(sequelizeConfig);
        await sequelize.authenticate();
        console.log("Database connection successful through SSH tunnel.");
    
        // 同步模型
        await sequelize.sync({ alter: true });
      } catch (error) {
        console.error("Unable to connect to the database:", error);
      }

    // 验证数据库连接
    const sequelize = new Sequelize(sequelizeConfig);
    await sequelize.authenticate();
    app.context.sequelize = sequelize;
    await app.model.sync({
      alter: true,
    });
    console.log("Database connection successful through SSH tunnel.");

    // 同步模型等其他操作...
    // await sequelize.sync({ alter: true });

    // 记得在适当的时候关闭SSH隧道，比如应用退出时
    process.on("SIGINT", () => {
      server.close(() => {
        console.log("SSH tunnel closed.");
        process.exit(0);
      });
    });
  } catch (error) {
    console.error(
      "Error during SSH tunnel setup or database connection:",
      error
    );
  }
};
